package com.arsn.myf.common.util.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.DateUtils;
import com.arsn.myf.common.excel.RowWriteHandler;
import com.arsn.myf.common.exception.ExcelException;
import com.arsn.myf.common.excel.ExcelImporter;
import com.arsn.myf.common.excel.ImportListener;
import org.apache.commons.codec.Charsets;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * 导出工具类
 * @author zhongrj
 * @since 2021-12-05
 */
public class ExcelUtil {

    /**
     * 导入数据保存
     * @param excel
     * @param importer
     * @param clazz
     * @param <T>
     */
    public static <T> void save(MultipartFile excel, ExcelImporter<T> importer, Class<T> clazz) {
        ImportListener<T> importListener = new ImportListener(importer);
        ExcelReaderBuilder builder = getReaderBuilder(excel, importListener, clazz);
        if (builder != null) {
            builder.doReadAll();
        }
    }

    /**
     * 导出数据到 excel
     * @param response
     * @param dataList
     * @param clazz
     * @param <T>
     */
    public static <T> void export(HttpServletResponse response,String fileName, List<T> dataList, Class<T> clazz){
        export(response,fileName + DateUtils.format(new Date(), "yyyyMMddHHmmss"), "导出数据", dataList, clazz);
    }

    /**
     * 导出数据到 excel
     * @param response
     * @param fileName
     * @param sheetName
     * @param dataList
     * @param clazz
     * @param <T>
     */
    public static <T> void export(HttpServletResponse response, String fileName, String sheetName, List<T> dataList, Class<T> clazz){
        try {
            //新增  Content-Disposition 暴露到前端，否则无法显示
            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
            fileName = URLEncoder.encode(fileName, Charsets.UTF_8.name());
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding(Charsets.UTF_8.name());
            EasyExcel.write(response.getOutputStream(), clazz).sheet(sheetName).registerWriteHandler(new RowWriteHandler()).doWrite(dataList);
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取 ExcelReaderBuilder
     * @param excel
     * @param readListener
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> ExcelReaderBuilder getReaderBuilder(MultipartFile excel, ReadListener<T> readListener, Class<T> clazz) {
        String filename = excel.getOriginalFilename();
        if (StringUtils.isEmpty(filename)) {
            throw new ExcelException("请上传文件!");
        } else if (!StringUtils.endsWithIgnoreCase(filename, ".xls") && !StringUtils.endsWithIgnoreCase(filename, ".xlsx")) {
            throw new ExcelException("请上传正确的excel文件!");
        } else {
            try {
                InputStream inputStream = new BufferedInputStream(excel.getInputStream());
                return EasyExcel.read(inputStream, clazz, readListener);
            } catch (Exception e){
                e.printStackTrace();
                return null;
            }
        }
    }
}

